/*
 * Copyright (C) 2015-2017 Alibaba Group Holding Limited
 */

#include <k_api.h>
#include <assert.h>
#include <stdio.h>
#include "fsl_device_registers.h"

#if (RHINO_CONFIG_HW_COUNT > 0)
void soc_hw_timer_init(void)
{
}

hr_timer_t soc_hr_hw_cnt_get(void)
{
    return 0;
}

lr_timer_t soc_lr_hw_cnt_get(void)
{
    return 0;
}
#endif /* RHINO_CONFIG_HW_COUNT */

#if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0)
void soc_intrpt_stack_ovf_check(void)
{
}
#endif

size_t soc_get_cur_sp()
{
    size_t sp = 0;
#if defined (__GNUC__)&&!defined(__CC_ARM)
    asm volatile(
        "mov %0,sp\n"
        :"=r"(sp));
#endif
    return sp;
}


static void soc_print_stack()
{
    void    *cur, *end;
    int      i=0;
    int     *p;

    end   = krhino_cur_task_get()->task_stack_base + krhino_cur_task_get()->stack_size;
    cur = (void *)soc_get_cur_sp();
    p = (int*)cur;
    while(p < (int*)end) {
        if(i%4==0) {
            printf("\r\n%08x:",(uint32_t)p);
        }
        printf("%08x ", *p);
        i++;
        p++;
    }
    printf("\r\n");
    return;
}

void soc_err_proc(kstat_t err)
{
    (void)err;
    soc_print_stack();
    assert(0);
}

krhino_err_proc_t g_err_proc = soc_err_proc;

#if (RHINO_CONFIG_MM_TLF > 0)
k_mm_region_t g_mm_region[2] = {0};
int           g_region_num = 2;

#if defined (__CC_ARM)

extern unsigned int Image$$RW_m_data$$ZI$$Limit;
extern unsigned int Image$$ARM_LIB_STACK$$ZI$$Base;
void aos_heap_set()
{
    g_mm_region[0].start = &Image$$RW_m_data$$ZI$$Limit;
    g_mm_region[0].len   = ((uint8_t*)&Image$$ARM_LIB_STACK$$ZI$$Base - (uint8_t*)&Image$$RW_m_data$$ZI$$Limit);
    /*ocram  default is 256 + 512KB */
    g_mm_region[1].start = 0x20200000;
    g_mm_region[1].len   = 0x000C0000;
}

#if 0
extern unsigned int Image$$RW_IRAM1$$ZI$$Limit;
extern size_t g_iram1_start;
extern size_t g_iram1_total_size;

void aos_heap_set()
{

    g_mm_region[0].start = (uint8_t*)&Image$$RW_IRAM1$$ZI$$Limit;
    g_mm_region[0].len   = 
        (g_iram1_start + g_iram1_total_size - (size_t)&Image$$RW_IRAM1$$ZI$$Limit);
}
#endif
#elif defined (__ICCARM__)
extern uint32_t __ICFEDIT_region_RAM_end__;
extern void* CSTACK$$Limit;
#pragma section = "CSTACK"

void aos_heap_set()
{
    g_mm_region[0].start = (uint8_t *)(&CSTACK$$Limit);    /* heap defined by array*/
    g_mm_region[0].len   = (size_t)(&__ICFEDIT_region_RAM_end__) - (size_t)(&CSTACK$$Limit);
}

#else
extern void         *__bss_end__;
extern void         *__StackLimit;

void aos_heap_set()
{

#if 0
    g_mm_region[0].start = (uint8_t*)&__bss_end__;
    g_mm_region[0].len   =
        ((uint8_t*)&__StackLimit - (uint8_t*)&__bss_end__);
#else
    /*ocram  default is 256KB */
    g_mm_region[0].start = (uint8_t*)&__bss_end__;
    g_mm_region[0].len   = (size_t)((uint8_t*)&__StackLimit - (uint8_t*)&__bss_end__);
    /*sdram  16MB*/
    g_mm_region[1].start = (uint8_t*)0x20200000;
    g_mm_region[1].len   = (size_t)0x000C0000;

#endif
}

#endif

#endif

